﻿using LD.Host;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace LD.Tool
{
    public partial class VmGlobalWriteFrm : FrmToolBase
    {
        public VmGlobalWriteFrm()
        {
            InitializeComponent();

            this.Text = TB_Tool.Name;
            this.btn_ok.Click += Btn_ok_Click;
            this.Shown += ToolReadImageFrm_Shown;
        }

        private void ToolReadImageFrm_Shown(object sender, EventArgs e)
        {
            Init();
        }

        private void Btn_ok_Click(object sender, EventArgs e)
        {
            List<VmGlobalParam> globals = new List<VmGlobalParam>();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (DataGridViewRow item in this.dgv_data.Rows)
            {
                if (item.Cells["视觉地址"].Value != null
                    && item.Cells["PLC地址"].Value != null
                    && item.Cells["PLC数据类型"].Value != null
                    && !string.IsNullOrEmpty(item.Cells["视觉地址"].Value.ToString())
                    && !string.IsNullOrEmpty(item.Cells["PLC地址"].Value.ToString())
                    && !string.IsNullOrEmpty(item.Cells["PLC数据类型"].Value.ToString())
                    )
                {
                    globals.Add(new VmGlobalParam()
                    {
                        PlcAddress = item.Cells["PLC地址"].Value.ToString(),
                        CCDGlobal = item.Cells["视觉地址"].Value.ToString(),
                        PlcDataType = item.Cells["PLC数据类型"].Value.ToString(),
                    });
                }
            }
            var _param = Newtonsoft.Json.JsonConvert.SerializeObject(globals);
            TB_Tool.Param = _param;
        }

        private void Init()
        {
            if (TB_Tool.Param == null)
                return;
            var param = Newtonsoft.Json.JsonConvert.DeserializeObject<List<VmGlobalParam>>(TB_Tool.Param);
            if (param != null)
            {
                foreach (var item in param)
                {
                    int index = this.dgv_data.Rows.Add();
                    this.dgv_data["视觉地址", index].Value = item.CCDGlobal;
                    this.dgv_data["PLC地址", index].Value = item.PlcAddress;
                    this.dgv_data["PLC数据类型", index].Value = item.PlcDataType;
                }
            }
        }
    }
}
